/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 * 工具类包，版本1.8
 * （注意：覆盖时一定要看清楚版本是否正确）
 * uuid()：返回唯一id
 * fullForm({form"表单的jquery引用",data"需要填充的数据",filter"过虑器不需要填充的数据",nameSpace"名字空间的分隔符号"})：填充表单
 * formToObj($form);
 * parseTimestamp:处理时间日期
 * nameSpace:名字空间。例如：webUtils.nameSpace("wiseMen.platform")
 * topicPublish:发布主题    topics, args
 * topicSubscribe:订阅主题 topics, func
 * topicUnSubscribe:取消订阅 token
 * getServerTime:获取系统时间
 * orgSelector:组织机构选择工具
 * orgSelectHook:通用组织机构选择钩子
 * userSelector:用户选择工具
 * roleSelector:角色选择工具
 * fileUploader:文件上传工具
 * getCurrentUser:获取当前用户信息
 * hasAllRoles:是否包括所有角色
 * hasAnyRoles:是否包括其中某些角色
 * hasAllPermissions:是否包括所有权限
 * hasAnyPermissions:是否包括某些权限
 * getMenuById:获取菜单
 * getMenuByCode:通过code获取菜单
 * getUserSubMenuById:通过id获取用户菜单
 * getUserSubMenuByCode:通过code获取用户菜单
 * triggerOnMenu:菜单点击触发
 * getShortPinyin:拼音短名
 * getDataDicItemVal:function(dicCode,itemCode):字典值编码,字典项编码
 * getDataDicItems:function(dicCode):字典值编码
 */
(function () {
	window.webUtils = {
        topics: {},
        topicPublish: function (topics, args,isAutoRemove) {
            var topicList = topics.split(",");
            if (typeof topicList == 'string') {
                topicList = [topicList];
            }

            $.each(topicList, function (i, topic) {
                if (webUtils.topics[topic]) {
                    var subs = webUtils.topics[topic];
                    $.each(subs, function (i, sub) {
                        sub.func.call(null, args);
                        if(sub.isAutoRemove){
                        	sub.remove();
                        }
                        if(isAutoRemove){
                        	sub.remove();
                        }
                    });
                }
            });
        },
        topicSubscribe: function (topics, func,isAutoRemove) {
            var topicList = topics.split(",");
            if (typeof topicList == 'string') {
                topicList = [topicList];
            }

            var uuid = webUtils.uuid();
            var sub = function () {
                this.topics = topics;
                this.uuid = uuid;
                this.func = func;
                this.isAutoRemove=isAutoRemove;
                this.remove = function () {
                    var me = this;
                    if(!me.hasRemoved){
                    	$.each(topicList, function (i, topic) {
                            delete webUtils.topics[topic][me.uuid];
                            me.hasRemoved=true;
                        });
                    }
                    
                };
            };

            var subObj = new sub();

            $.each(topicList, function (i, topic) {
                if (!webUtils.topics[topic]) {
                    webUtils.topics[topic] = {};
                }

                webUtils.topics[topic][uuid] = subObj;
            });
            return subObj;
        },
        
        uuid: function () {
            var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
            var uuid = new Array(36),
                    rnd = 0,
                    r;
            for (var i = 0; i < 36; i++) {
                if (i == 8 || i == 13 || i == 18 || i == 23) {
                    uuid[i] = "-";
                } else if (i == 14) {
                    uuid[i] = "4";
                } else {
                    if (rnd <= 0x02) {
                        rnd = 0x2000000 + (Math.random() * 0x1000000) | 0;
                    }
                    r = rnd & 0xf;
                    rnd = rnd >> 4;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
            return uuid.join("");
        },
        disableEdit:function(arg){
            var form = arg.form;
            form.find("input,textarea,select").attr("disabled","disabled");
        },
        fullForm: function (arg) {
            var form = arg.form;

            var filterStr = "";
            if (arg.filter) {
                filterStr = arg.filter.join("|") + '|';
            }

            var nameSpace = "";
            if (arg.nameSpace) {
                nameSpace = arg.nameSpace + ".";
            }

            var data = arg.data;
            for (var name in data) {
                if (filterStr.indexOf(name + '|') != -1) {
                    continue;
                }
                var val = data[name];

                if (!!val && (typeof val) == "object") {
                    if (val.time) {
                        val = webUtils.parseTimestamp(val);
                    } else {
                        webUtils.fullForm({
                            form: form,
                            data: val,
                            filter: arg.filter,
                            nameSpace: nameSpace + name
                        });
                        continue;
                    }
                }

                if ($('input[name="' + nameSpace + name + '"]:checkbox ', form).size() > 0 ) {
                	if(val){
                		var vals=String(val).split(",");
                    	$.each(vals,function(i,n){
                    		if(n!=''){
	                    		var c = $('input[name="' + nameSpace + name + '"][value=' + n + ']:checkbox ', form);
	                            c.attr("checked", true);
                    		}
                    	})
                	}
                	continue;
                }
                if ($('input[name="' + nameSpace + name + '"]:radio ', form).size() > 0) {
                	if(val){
	                	var vals=String(val).split(",");
	                	$.each(vals,function(i,n){
	                		if(n!=''){
	                			var c = $('input[name="' + nameSpace + name + '"][value=' + n + ']:radio ', form);
		                        c.attr("checked", true);
	                		}
	                	});
                	}
                    continue;
                }

                $('input[name="' + nameSpace + name + '"]', form).val(val);
                $('textarea[name="' + nameSpace + name + '"]', form).val(val);
                $('select[name="' + nameSpace + name + '"]', form).val(val);
                $('span[name="' + nameSpace + name + '"]', form).html(val);
                $('p[name="' + nameSpace + name + '"]', form).html(val);

            }
        },
        /**
         * 表单对象转json对象
         */
        formToObj:function(form){
            var a=form.formToArray(true);
            var o={};
            
            $.each(a,function(i,n){
            	var co=o;
            	var names=this.name.split(".");
            	if(names.length>1){
            		$.each(names,function(si,sn){
            			if(si<names.length-1){
	            			if(typeof o[sn] == 'undefined'){
	            				o[sn]={};
	            			}
	            			o= o[sn];
            			}else if(si==names.length-1){
            				if (o[sn]) {
         	    	           if (!o[sn].push) {  
         	    	        	   o[sn] = [o[sn]];  
         	    	           }  
         	    	           o[sn].push(n.value || '');  
         	    	       } else {  
         	    	    	   o[sn] = n.value || '';  
         	    	       }
            			}
            		});
            		o=co;
            	}else{
	            	if (o[this.name]) {
	    	           if (!o[this.name].push) {  
	    	        	   o[this.name] = [o[this.name]];  
	    	           }  
	    	           o[this.name].push(this.value || '');  
	    	       } else {  
	    	    	   o[this.name] = this.value || '';  
	    	       }  
            	}
            });
            return o;
        },
        /**
         *     
         * 对Date的扩展，将 Date 转化为指定格式的String      
         * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符      
         * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)      
         * eg:      
         * WebAppUtils.parseTimestamp(new Date(),"yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423      
         * WebAppUtils.parseTimestamp(new Date(),"yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04      
         * WebAppUtils.parseTimestamp(new Date(),"yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04      
         * WebAppUtils.parseTimestamp(new Date(),"yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04      
         * WebAppUtils.parseTimestamp(new Date(),"yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18     
         * @param time	因为在js中new Date().getTime()少了微秒，所以要乘以1000
         * @param fmt
         * @returns
         */
        parseTimestamp: function (time, fmt) {
        	if(!time){
        		return "";
        	}
            var d;
            if (typeof time == 'string') {
                time = time.replace(/\-/g, "/");
                d = new Date(time);
            } else if (typeof time == 'number') {
                d = new Date(time);
            } else if (typeof time == 'object') {
                if (time.getTime) {
                    d = time;
                } else {
                    d = new Date(time.time);
                }

            }
            fmt = fmt ? fmt : "yyyy-MM-dd";
            var o = {
                "M+": d.getMonth() + 1, //月份         
                "d+": d.getDate(), //日         
                "h+": d.getHours() % 12 == 0 ? 12 : d.getHours() % 12, //小时         
                "H+": d.getHours(), //小时         
                "m+": d.getMinutes(), //分         
                "s+": d.getSeconds(), //秒         
                "q+": Math.floor((d.getMonth() + 3) / 3), //季度         
                "S": d.getMilliseconds() //毫秒         
            };
            var week = {
                "0": "\u65e5",
                "1": "\u4e00",
                "2": "\u4e8c",
                "3": "\u4e09",
                "4": "\u56db",
                "5": "\u4e94",
                "6": "\u516d"
            };
            if (/(y+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            if (/(E+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[d.getDay() + ""]);
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                }
            }
            return fmt;
        },
        //秒转换为时分秒
        formatSeconds: function (value) {
        	var theTime = parseInt(value);// 秒
        	var theTime1 = 0;// 分
        	var theTime2 = 0;// 小时
        	if(theTime > 60) {
    	    	theTime1 = parseInt(theTime/60);
    	    	theTime = parseInt(theTime%60);
    	    	if(theTime1 > 60) {
    		    	theTime2 = parseInt(theTime1/60);
    		    	theTime1 = parseInt(theTime1%60);
    	    	}
        	}
        	var result = ""+parseInt(theTime)+"秒";
        	if(theTime1 > 0) {
        		result = ""+parseInt(theTime1)+"分"+result;
        	}
        	if(theTime2 > 0) {
        		result = ""+parseInt(theTime2)+"小时"+result;
        	}
        	return result;
        },
        md5:function(string){
            function md5_RotateLeft(lValue, iShiftBits) {
                    return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
            }
            function md5_AddUnsigned(lX,lY){
                    var lX4,lY4,lX8,lY8,lResult;
                    lX8 = (lX & 0x80000000);
                    lY8 = (lY & 0x80000000);
                    lX4 = (lX & 0x40000000);
                    lY4 = (lY & 0x40000000);
                    lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
                    if (lX4 & lY4) {
                            return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
                    }
                    if (lX4 | lY4) {
                            if (lResult & 0x40000000) {
                                    return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
                            } else {
                                    return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
                            }
                    } else {
                            return (lResult ^ lX8 ^ lY8);
                    }
            }         
            function md5_F(x,y,z){
                    return (x & y) | ((~x) & z);
            }
            function md5_G(x,y,z){
                    return (x & z) | (y & (~z));
            }
            function md5_H(x,y,z){
                    return (x ^ y ^ z);
            }
            function md5_I(x,y,z){
                    return (y ^ (x | (~z)));
            }
            function md5_FF(a,b,c,d,x,s,ac){
                    a = md5_AddUnsigned(a, md5_AddUnsigned(md5_AddUnsigned(md5_F(b, c, d), x), ac));
                    return md5_AddUnsigned(md5_RotateLeft(a, s), b);
            }; 
            function md5_GG(a,b,c,d,x,s,ac){
                    a = md5_AddUnsigned(a, md5_AddUnsigned(md5_AddUnsigned(md5_G(b, c, d), x), ac));
                    return md5_AddUnsigned(md5_RotateLeft(a, s), b);
            };
            function md5_HH(a,b,c,d,x,s,ac){
                    a = md5_AddUnsigned(a, md5_AddUnsigned(md5_AddUnsigned(md5_H(b, c, d), x), ac));
                    return md5_AddUnsigned(md5_RotateLeft(a, s), b);
            }; 
            function md5_II(a,b,c,d,x,s,ac){
                    a = md5_AddUnsigned(a, md5_AddUnsigned(md5_AddUnsigned(md5_I(b, c, d), x), ac));
                    return md5_AddUnsigned(md5_RotateLeft(a, s), b);
            };
            function md5_ConvertToWordArray(string) {
                    var lWordCount;
                    var lMessageLength = string.length;
                    var lNumberOfWords_temp1=lMessageLength + 8;
                    var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
                    var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
                    var lWordArray=Array(lNumberOfWords-1);
                    var lBytePosition = 0;
                    var lByteCount = 0;
                    while ( lByteCount < lMessageLength ) {
                            lWordCount = (lByteCount-(lByteCount % 4))/4;
                            lBytePosition = (lByteCount % 4)*8;
                            lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
                            lByteCount++;
                    }
                    lWordCount = (lByteCount-(lByteCount % 4))/4;
                    lBytePosition = (lByteCount % 4)*8;
                    lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
                    lWordArray[lNumberOfWords-2] = lMessageLength<<3;
                    lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
                    return lWordArray;
            }; 
            function md5_WordToHex(lValue){
                    var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
                    for(lCount = 0;lCount<=3;lCount++){
                            lByte = (lValue>>>(lCount*8)) & 255;
                            WordToHexValue_temp = "0" + lByte.toString(16);
                            WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
                    }
                    return WordToHexValue;
            };
            function md5_Utf8Encode(string){
                    string = string.replace(/\r\n/g,"\n");
                    var utftext = ""; 
                    for (var n = 0; n < string.length; n++) {
                            var c = string.charCodeAt(n); 
                            if (c < 128) {
                                    utftext += String.fromCharCode(c);
                            }else if((c > 127) && (c < 2048)) {
                                    utftext += String.fromCharCode((c >> 6) | 192);
                                    utftext += String.fromCharCode((c & 63) | 128);
                            } else {
                                    utftext += String.fromCharCode((c >> 12) | 224);
                                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                                    utftext += String.fromCharCode((c & 63) | 128);
                            } 
                    } 
                    return utftext;
            }; 
            var x=Array();
            var k,AA,BB,CC,DD,a,b,c,d;
            var S11=7, S12=12, S13=17, S14=22;
            var S21=5, S22=9 , S23=14, S24=20;
            var S31=4, S32=11, S33=16, S34=23;
            var S41=6, S42=10, S43=15, S44=21;
            string = md5_Utf8Encode(string);
            x = md5_ConvertToWordArray(string); 
            a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476; 
            for (k=0;k<x.length;k+=16) {
                    AA=a; BB=b; CC=c; DD=d;
                    a=md5_FF(a,b,c,d,x[k+0], S11,0xD76AA478);
                    d=md5_FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
                    c=md5_FF(c,d,a,b,x[k+2], S13,0x242070DB);
                    b=md5_FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
                    a=md5_FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
                    d=md5_FF(d,a,b,c,x[k+5], S12,0x4787C62A);
                    c=md5_FF(c,d,a,b,x[k+6], S13,0xA8304613);
                    b=md5_FF(b,c,d,a,x[k+7], S14,0xFD469501);
                    a=md5_FF(a,b,c,d,x[k+8], S11,0x698098D8);
                    d=md5_FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
                    c=md5_FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
                    b=md5_FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
                    a=md5_FF(a,b,c,d,x[k+12],S11,0x6B901122);
                    d=md5_FF(d,a,b,c,x[k+13],S12,0xFD987193);
                    c=md5_FF(c,d,a,b,x[k+14],S13,0xA679438E);
                    b=md5_FF(b,c,d,a,x[k+15],S14,0x49B40821);
                    a=md5_GG(a,b,c,d,x[k+1], S21,0xF61E2562);
                    d=md5_GG(d,a,b,c,x[k+6], S22,0xC040B340);
                    c=md5_GG(c,d,a,b,x[k+11],S23,0x265E5A51);
                    b=md5_GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
                    a=md5_GG(a,b,c,d,x[k+5], S21,0xD62F105D);
                    d=md5_GG(d,a,b,c,x[k+10],S22,0x2441453);
                    c=md5_GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
                    b=md5_GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
                    a=md5_GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
                    d=md5_GG(d,a,b,c,x[k+14],S22,0xC33707D6);
                    c=md5_GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
                    b=md5_GG(b,c,d,a,x[k+8], S24,0x455A14ED);
                    a=md5_GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
                    d=md5_GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
                    c=md5_GG(c,d,a,b,x[k+7], S23,0x676F02D9);
                    b=md5_GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
                    a=md5_HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
                    d=md5_HH(d,a,b,c,x[k+8], S32,0x8771F681);
                    c=md5_HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
                    b=md5_HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
                    a=md5_HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
                    d=md5_HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
                    c=md5_HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
                    b=md5_HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
                    a=md5_HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
                    d=md5_HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
                    c=md5_HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
                    b=md5_HH(b,c,d,a,x[k+6], S34,0x4881D05);
                    a=md5_HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
                    d=md5_HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
                    c=md5_HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
                    b=md5_HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
                    a=md5_II(a,b,c,d,x[k+0], S41,0xF4292244);
                    d=md5_II(d,a,b,c,x[k+7], S42,0x432AFF97);
                    c=md5_II(c,d,a,b,x[k+14],S43,0xAB9423A7);
                    b=md5_II(b,c,d,a,x[k+5], S44,0xFC93A039);
                    a=md5_II(a,b,c,d,x[k+12],S41,0x655B59C3);
                    d=md5_II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
                    c=md5_II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
                    b=md5_II(b,c,d,a,x[k+1], S44,0x85845DD1);
                    a=md5_II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
                    d=md5_II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
                    c=md5_II(c,d,a,b,x[k+6], S43,0xA3014314);
                    b=md5_II(b,c,d,a,x[k+13],S44,0x4E0811A1);
                    a=md5_II(a,b,c,d,x[k+4], S41,0xF7537E82);
                    d=md5_II(d,a,b,c,x[k+11],S42,0xBD3AF235);
                    c=md5_II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
                    b=md5_II(b,c,d,a,x[k+9], S44,0xEB86D391);
                    a=md5_AddUnsigned(a,AA);
                    b=md5_AddUnsigned(b,BB);
                    c=md5_AddUnsigned(c,CC);
                    d=md5_AddUnsigned(d,DD);
            }
    return (md5_WordToHex(a)+md5_WordToHex(b)+md5_WordToHex(c)+md5_WordToHex(d)).toLowerCase();
},
        nameSpace: function (name) {
            var parts = name.split('.');
            var namespace = window;
            $.each(parts, function (i, n) {
                if (typeof namespace[n] == 'undefined') {
                    namespace[n] = {};
                }
                namespace = namespace[n];
            });
        },
        getServerTime: function () {
            var date = new Date($.ajax({async: false}).getResponseHeader("Date"));
            var bombay = date + (3600000 * 8);
            var time = new Date(bombay);
            return time;
        },
        roleSelector:function(params){
        	require(['wiseMen/module/RoleSelector'],function(roleSelector){
        		new roleSelector(params);
        	});
        },
        orgSelector: function (params) {
        	require(['wiseMen/module/OrgUserSelector'],function(orgUserSelector){
        		new orgUserSelector.orgSelector(params);
        	});
        },
        adminDivSelector: function (params) {
        	require(['wiseMen/module/AdminDivSelector'],function(adminDivSelector){
        		new adminDivSelector(params);
        	});
        },
        adminDivQuery: function (codes) {
        	if($.isArray(codes)){
        		codes=codes.join(",");
        	}
        	var result;
        	$.ajax({
                type: "GET",
                url: ctx + "/adminDivAct/queryByCodes.do",
                async: false,
                data:{codes:codes},
                dataType: 'json',
                success: function (ds) {
                	result=ds;
                }
            });
        	return result;
        },
        adminDivQueryNameStr: function (codes) {
        	var result=[];
        	var r=webUtils.adminDivQuery(codes);
        	$.each(r,function(i,n){
        		result.push(n.name);
        	})
        	return result.join(",");
        },
        orgSelectHook: function (params) {
            var form=$(params.formSelector);
            $(params.selectHookSelector).click(function () {
                var hasSelectedOrgs = [];
                var mainDeptIds = form.find(params.idHookSelector).val();
                if (mainDeptIds) {
                    mainDeptIds = $.parseJSON(mainDeptIds);
                    $.each(mainDeptIds, function (i, n) {
                        hasSelectedOrgs.push({
                            id: n.id,
                            name: n.name
                        });
                    });
                }

                var names = [];
                var json = [];
                webUtils.orgSelector({
                    hasSelectedOrgs: hasSelectedOrgs,
                    onSelect: function (rows) {
                        $.each(rows, function (i, n) {
                            names.push(n.name);
                            json.push({
                                id: n.id,
                                name: n.name,
                                type: 1
                            });
                        });
                        form.find(params.idHookSelector).val(JSON.stringify(json));
                        form.find(params.nameHookSelector).val(names.join(","));
                    }
                });
            });
        },
        userSelector: function (params) {
        	require(['wiseMen/module/OrgUserSelector'],function(orgUserSelector){
        		new orgUserSelector.userSelector(params);
        	});
        },
        dataDicSelector: function (params) {
        	require(['wiseMen/module/DataDicSelector'],function(dataDicSelector){
        		new dataDicSelector(params);
        	});
        },
        /**
         * 参数:
         * onFileQueued(file)
         * onUploadProgress(file,percentage)
         * onUploadSuccess(file)
         * onUploadError(file)
         * onUploadComplete(file)
         */
        fileUploader: function (params) {
        	require(['wiseMen/module/FileUploader'],function(FileUploader){
        		new FileUploader(params);
        	});
        },
        fileLoader: function (params) {
        	require(['wiseMen/module/FileLoader'],function(FileLoader){
        		new FileLoader(params);
        	});
        },
        delFile:function(attId,domId){
        	webUtils.confirm("删除后将不可恢复，请问是否继续?", function(result) {
				if(result){
					$.post(ctx+"/attachmentAction/deleteAtt.do",{id:attId},function(data){
		        		if(data.success){
		        			$("#"+domId).remove();
		        		}else {
	                    	webUtils.alert(data.msg);
	                    }
		        	},"json");
				}
        	});
        },
        downloadFile:function(attId){
        	window.open(ctx+"/attachmentAction/download.do?id="+attId)
        },
        getCurrentUser: function () {
            if (webUtils.currentUser) {
                return webUtils.currentUser;
            } else {
                $.ajax({
                    type: "GET",
                    url: ctx + "/userAction/findCurrentUser.do",
                    async: false,
                    dataType: 'json',
                    success: function (msg) {
                        webUtils.currentUser = msg;
                    }
                });
                return webUtils.currentUser;
            }
        },
        hasAllRoles: function (roles) {
            var result = true;
            var roleList = roles.split(",");
            var currentUser = webUtils.getCurrentUser();
            var myRoles = currentUser.roles.join(",");
            $.each(roleList, function (i, n) {
                if (myRoles.indexOf(n) < 0) {
                    result = false;
                    return false;
                }
            });
            return result;
        },
        hasAnyRoles: function (roles) {
            var result = false;
            var roleList = roles.split(",");
            var currentUser = webUtils.getCurrentUser();
            var myRoles = currentUser.roles.join(",");
            $.each(roleList, function (i, n) {
                if (myRoles.indexOf(n) >= 0) {
                    result = true;
                    return false;
                }
            });
            return result;
        },
        hasAllPermissions: function (permissions) {
            var result = true;
            var permissionList = permissions.split(",");
            var currentUser = webUtils.getCurrentUser();
            var myOptAuths = currentUser.optAuths.join(",");
            $.each(permissionList, function (i, n) {
                if (myOptAuths.indexOf(n) < 0) {
                    result = false;
                    return false;
                }
            });
            return result;
        },
        hasAnyPermissions: function (permissions) {
            var result = false;
            var permissionList = permissions.split(",");
            var currentUser = webUtils.getCurrentUser();
            var myOptAuths = currentUser.optAuths.join(",");
            $.each(permissionList, function (i, n) {
                if (myOptAuths.indexOf(n) >= 0) {
                    result = true;
                    return false;
                }
            });
            return result;
        },
        getMenuById: function (id, callback) {
            $.ajax({
                type: "GET",
                url: ctx + "/menuAction/getMenu.do",
                dataType: 'json',
                data: {id: id},
                success: callback
            });
        },
        getMenuByCode: function (code, sysFlag, callback) {
            $.ajax({
                type: "GET",
                url: ctx + "/menuAction/getMenuByCode.do",
                dataType: 'json',
                data: {code: code, sysFlag: sysFlag},
                success: callback
            });
        },
        getUserSubMenuById: function (id, sysFlag, callback,isGetAll) {
        	if(typeof isGetAll == "undefined"){
        		isGetAll=false;
        	}
            $.ajax({
                type: "GET",
                url: ctx + "/menuAction/loadUserMenus.do",
                dataType: 'json',
                data: {sysFlag: sysFlag, pid: id,isGetAll:isGetAll},
                success: callback
            });
        },
        getUserSubMenuByCode: function (code, sysFlag, callback) {
            $.ajax({
                type: "GET",
                url: ctx + "/menuAction/loadUserMenusByCode.do",
                dataType: 'json',
                data: {pCode: code, sysFlag: sysFlag},
                success: callback
            });
        },
        triggerOnMenu: function (menu, container) {
            if (menu.funcPoint) {
                if (menu.openType == 1) {
                    container.html("");
                    container.load(ctx + menu.funcPoint.url);
                } else if (menu.openType == 2) {
                    container.html("");
                    container.html('<iframe src="' + ctx + menu.funcPoint.url + '" scrolling="auto" frameborder="0" height="100%" width="100%" marginheight="0" marginwidth="0"></iframe>');
                    var iframe=container.find("iframe:first");
                    iframe.height($(window).height()*0.8);
                } else if (menu.openType == 3) {
                    window.open(ctx + menu.funcPoint.url);
                } else if (menu.openType == 4) {
                    window[menu.url].call(null,menu,container);
                }
            }
        },
        getShortPinyin:function(str,callback){
        	$.getJSON(ctx+"/pinyinAction/getShortPinyin.do",{
        		str:str
        	},function(data){
        		callback.call(null,data.result);
        	});
        },
        getEn:function(str,callback){
        	var salt=(new Date()).getTime();
        	$.ajax({ 
        		url:"http://api.fanyi.baidu.com/api/trans/vip/translate",
        		type: "GET", 
        		cache: false, 
        		dataType: "jsonp", 
        		data:{
        			appid:"20160213000011749",
        			salt:salt,
        			sign:webUtils.md5("20160213000011749"+str+salt+"ErCLGE0646vV96FHEuIf"),
	        		from:"zh",
	        		to:"en",
	        		q:str
	        	},
	        	success:function(data){
	        		callback.call(null,data.trans_result[0].dst.toLowerCase());
        	}
        	});
        },
        dataDics:{},
        getDataDicItems:function(dicCode,isGetAllOrg){
        	var dataDic=[];
        	isGetAllOrg=isGetAllOrg||true;
        	if(webUtils.dataDics[dicCode]){
        		dataDic=webUtils.dataDics[dicCode]
        	}else{
        		$.ajax({
        			url:ctx+"/dataDicAction/queryDataDicItems.do",
        			async:false,
        			data:{dataDicCode:dicCode,isGetAllOrg:isGetAllOrg},
        			dataType:"json",
        			success:function(data){
        				webUtils.dataDics[dicCode]=data;
        				dataDic=data;
        			}
        		});
        	}
        	return dataDic;
        },
        getDataDicItemVal:function(dicCode,itemCode){
        	var dataDic=[];
        	var val;
        	dataDic=webUtils.getDataDicItems(dicCode);
        	$.each(dataDic,function(i,n){
    			if(n.code==itemCode){
    				val=n;
    				return false;
    			}
    		})
        	return val;
        },
        alert:function(msg){
        	toastr.info(msg,null,{
        		
        	});
        },
        error:function(msg){
        	toastr.error(msg,null,{
        		
        	});
        },
        confirm:function(msg,callback){        	
        	return new wiseMen.platform.Dialog.confirm({
        		msg:msg,
        		callback:callback
        	});
        },
        prompt:function(title,callback){
        	return new wiseMen.platform.Dialog.prompt({
        		title:title,
        		callback:callback
        	});
        },
        dialog : function(params) {
        	return new wiseMen.platform.Dialog.dialog(params);
		},
		paramToObj : function(param) {
			var search = param.replace(/^\s+/, '').replace(/\s+$/, '').match(
					/([^?#]*)(#.*)?$/);// 提取location.search中'?'后面的部分
			if (!search) {
				return {};
			}
			var searchStr = search[1];
			var searchHash = searchStr.split('&');

			var ret = {};
			for (var i = 0, len = searchHash.length; i < len; i++) { // 这里可以调用each方法
				var pair = searchHash[i];
				if ((pair = pair.split('='))[0]) {
					var key = decodeURIComponent(pair.shift());
					var value = pair.length > 1 ? pair.join('=') : pair[0];
					if (value != undefined) {
						value = decodeURIComponent(value);
					}
					if (key in ret) {
						if (ret[key].constructor != Array) {
							ret[key] = [ ret[key] ];
						}
						ret[key].push(value);
					} else {
						ret[key] = value;
					}
				}
			}
			return ret;
		}
    };
	
$(function(){
	webUtils.nameSpace("wiseMen.platform");
	webUtils.on=webUtils.topicSubscribe;
	webUtils.fire=webUtils.topicPublish;
	
	$.ajaxSetup({
		cache:false,
		error : function(XHR, TS) {
			if(XHR.status==404){
				webUtils.alert("未找到请求的资源");
			}
		}
	});
	$(document).ajaxSuccess(function(event, xhr, settings) {
		if(xhr.responseJSON && xhr.responseJSON.infoCode == 401) {
			webUtils.alert("您的权限不足，无访问该资源");
		}
		return event;
	})
});
})();
